

import { Injectable, NestInterceptor, ExecutionContext, CallHandler, Inject } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import Ret from '../dto/ret';
import { Reflector } from '@nestjs/core';
import { MESSAGE_KEY } from '../decorator/const';

@Injectable()
export default class FormatResponseInterceptor implements NestInterceptor {
  @Inject()
  private reflector: Reflector
  
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const isFlag = this.reflector.get<boolean>(MESSAGE_KEY, context.getClass()) || this.reflector.get<boolean>(MESSAGE_KEY, context.getHandler());
    return next.handle().pipe(map(data => Ret.success(...(isFlag ? [null, data]: [data, null]))));
  }
}